<template>
  <div class="work-report-container">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <a-input
        v-model="flowCardNumber"
        placeholder="请输入工序流转单卡号"
        style="width: 300px"
        allow-clear
        @pressEnter="handleSearch"
      />
      <a-button type="primary" style="margin-left: 10px" @click="handleSearch">
        查询
      </a-button>
    </div>

    <!-- 报工内容区域 -->
    <div class="content-area">
      <a-card title="报工信息" :bordered="false">
        <div class="work-form">
          <a-empty v-if="!flowCardNumber" description="请输入工序流转单卡号查询报工信息" />
          <pro-table
            v-else
            ref="table"
            toolbar-title="工序信息"
            :row-key="rowKey"
            :request="tableRequest"
            :columns="columns"
            :pagination="false"
          >
            <template #action-slot="text, record">
              <!-- 第一行：操作按钮（开工/暂停/完工） -->
              <div style="margin-bottom: 8px;">
                <!-- 已完工状态（禁用） -->
                <a v-if="record.endTime" disabled style="color: grey; cursor: not-allowed;">
                  已完工
                </a>
                <!-- 未完工状态 -->
                <template v-else>
                  <!-- 开工/完工按钮 -->
                  <a
                    :class="record.startTime ? 'btn-stop' : 'btn-start'"
                    @click="handleTiming(record)"
                  >
                    {{ record.startTime ? '完工' : '开工' }}
                  </a>
                  <!-- 暂停/继续按钮（黄色） -->
                  <a
                    v-if="record.startTime && !record.endTime"
                    class="btn-pause"
                    @click="handlePause(record)"
                    style="margin-left: 8px;"
                  >
                    {{ record.isPaused ? '继续' : '暂停' }}
                  </a>

                  <!-- 完工确认模态框 -->
                  <a-modal
                    title="完工确认"
                    :visible="finishModalVisible"
                    @ok="handleFinishConfirm"
                    @cancel="finishModalVisible = false"
                  >
                    <a-form-model
                      ref="finishForm"
                      :model="finishForm"
                      :rules="finishFormRules"
                    >
                      <!-- 必填：完工数量 -->
                      <a-form-model-item label="完工数量" prop="finishedQuantity" required>
                        <a-input-number
                          v-model="finishForm.finishedQuantity"
                          :min="0"
                          :precision="0"
                          placeholder="必填"
                          style="width: 100%"
                        />
                      </a-form-model-item>

                      <!-- 选填：不良品数量 -->
                      <a-form-model-item label="不良品数量（可选）" prop="defectiveQuantity">
                        <a-input-number
                          v-model="finishForm.defectiveQuantity"
                          :min="0"
                          :max="finishForm.finishedQuantity || Infinity"
                          :precision="0"
                          placeholder="不良品数量"
                          style="width: 100%"
                        />
                      </a-form-model-item>

                      <!-- 选填：不良原因 -->
                      <a-form-model-item label="不良原因（可选）" prop="defectiveReason">
                        <a-textarea
                          v-model="finishForm.defectiveReason"
                          placeholder="不良原因"
                          :rows="3"
                        />
                      </a-form-model-item>
                    </a-form-model>
                  </a-modal>
                </template>
              </div>

              <div style="margin-bottom: 8px;">
                <a @click="handlePreview('finishedProductImage', record)">
                  <a-tooltip title="预览成品图片">
                    成品图片
                  </a-tooltip>
                </a>
                <a-divider type="vertical" />
                <a @click="handlePreview('processCard', record)">
                  <a-tooltip title="预览工艺卡片">
                    工艺卡
                  </a-tooltip>
                </a>
              </div>

              <!-- 第二行：预览按钮（程序单/工艺卡） -->
              <div style="margin-bottom: 8px;">
                <a @click="handlePreview('procedureSheet', record)">
                  <a-tooltip title="预览CNC程序单">
                    程序单
                  </a-tooltip>
                </a>
                <a-divider type="vertical" />
                <a @click="handlePreview('ncProgram', record)">
                  <a-tooltip title="预览CNC程序单">
                    NC程序
                  </a-tooltip>
                </a>
              </div>

              <!-- 第三行：耗时显示 -->
              <div v-if="record.startTime" class="time-display">
                耗时：{{ activeDurations[record.id] || formatDuration(record) }}
                <span v-if="record.isPaused" style="color: #faad14;">(已暂停)</span>
              </div>

              <!-- PDF预览模态框 -->
              <PdfViewer
                ref="pdfViewer"
                :pdfUrl="previewUrl"
              />
            </template>
          </pro-table>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script>
import ProTable from '@/components/Table/ProTable.js'
import { getProcess } from '@/api/ProductionProcesses/t-process-flow-card'
import {
  updateStartTimer,
  updateEndTimer,
  getCncProgramFile, getPlmProgramFileNC
} from '@/api/ProductionProcesses/t-time-segment-record'
import {
  updatePauseTimer,
  updateResumeTimer
} from '@/api/ProductionProcesses/t-time-segment-pause'
import { USER_INFO } from '@/store/storage-types'
import { formatToLocalDateTime } from '@/utils/date.js'
import PdfViewer from '@/views/workreport/PdfViewer2.vue'
import Vue from 'vue'

export default {
  name: 'WorkReport',
  components: {
    ProTable,
    PdfViewer
  },
  data() {
    return {
      flowCardNumber: '',
      rowKey: 'id',
      activeTimers: {},      // 存储所有定时器
      activeDurations: {},   // 存储动态计算的耗时
      timerInterval: 1000,  // 更新频率(毫秒)
      previewUrl: '',
      columns: [
        { title: '#', dataIndex: 'id' },
        { title: '流转卡号', dataIndex: 'flowCardNumber' },
        { title: '工序序号', dataIndex: 'processSequence' },
        { title: '工序编码', dataIndex: 'processCode' },
        { title: '工序名称', dataIndex: 'processName' },
        { title: '准备工时(分钟)', dataIndex: 'setupTime' },
        { title: '标准工时(分钟)', dataIndex: 'standardTime' },
        { title: '总数量', dataIndex: 'totalQuantity' },
        { title: '完工数量', dataIndex: 'completedQuantity' },
        { title: '报废数量', dataIndex: 'scrappedQuantity' },
        { title: '状态', dataIndex: 'statusMsg' },
        {
          title: '操作',
          key: 'operate',
          align: 'center',
          width: '180px',
          scopedSlots: { customRender: 'action-slot' }
        }
      ],
      // 新增的数据属性
      finishModalVisible: false,
      finishForm: {
        processId: null,
        finishedQuantity: null,
        defectiveQuantity: null,
        defectiveReason: null
      },
      finishFormRules: {
        finishedQuantity: [
          { required: true, message: '请输入完工数量', trigger: 'blur' },
          { validator: (_, value, callback) => {
              if (value === null || value === undefined || value < 0) {
                callback(new Error('必须输入有效数字（≥0）'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        // 不良品数量改为选填（只需验证格式，不验证必填）
        defectiveQuantity: [
          { validator: (_, value, callback) => {
              if (value !== null && value !== undefined) {
                if (value < 0) {
                  callback(new Error('不能为负数'));
                }
              }
              callback();
            }, trigger: 'blur' }
        ],
        // 不良原因改为选填（无规则）
        defectiveReason: []
      }
    }
  },
  beforeDestroy() {
    // 清除所有定时器
    this.clearAllTimers()
  },
  mounted() {
    const params = this.$route.query
    console.log(this.$route.query)
    if (params.flowCardNumber) {
      this.flowCardNumber = params.flowCardNumber
      this.handleSearch()
    }
  },
  methods: {
    /**
     * 清除所有定时器
     */
    clearAllTimers() {
      Object.keys(this.activeTimers).forEach(id => {
        clearInterval(this.activeTimers[id])
        this.$delete(this.activeTimers, id)
        this.$delete(this.activeDurations, id)
      })
    },

    /**
     * 重新加载表格数据
     */
    reloadPageTable(withFirstPage = true) {
      this.$refs.table?.reloadTable?.(withFirstPage)
    },

    /**
     * 自定义表格请求方法
     */
    async tableRequest(params) {
      try {
        const res = await getProcess(this.flowCardNumber, params)
        // 数据加载完成后检查所有需要计时的记录
        this.$nextTick(() => {
          this.checkAllTimers(res.data)
        })
        return res
      } catch (error) {
        console.error('获取工序数据失败:', error)
        throw error
      }
    },

    /**
     * 检查所有记录并启动需要的定时器
     */
    checkAllTimers(data) {
      if (!data?.records) return

      data.records.forEach(record => {
        // 已开始但未结束且未暂停的记录需要计时
        if (record.startTime && !record.endTime && !record.isPaused) {
          this.startTimer(record)
        }
      })
    },

    /**
     * 处理暂停/继续操作
     */
    async handlePause(record) {
      try {
        if (!record.isPaused) {

          record.pauseStartTime = new Date()


          // 调用后端暂停接口
          const pauseResponse = await updatePauseTimer({
            recordId: record.id,
            pauseStart: formatToLocalDateTime(record.pauseStartTime),
            createName: Vue.ls.get(USER_INFO).username,

          })

          if (pauseResponse.code != 200){
            this.$message.warn(pauseResponse.message)
          }else {
            // 暂停逻辑
            this.stopTimer(record.id)
            record.isPaused = true
            record.pauseId = pauseResponse.data

            this.$message.success('已暂停计时')
          }

        } else {

          if (!record.pauseId) {
            throw new Error('缺少暂停记录ID')
          }

          // 继续逻辑
          const pauseEndTime = new Date()
          const pauseDuration = pauseEndTime - record.pauseStartTime
          record.totalPausedTime = (record.totalPausedTime || 0) + pauseDuration

          // 调用后端继续接口
          await updateResumeTimer({
            id: record.pauseId,
            pauseEnd: formatToLocalDateTime(pauseEndTime)
          })

          // 清除pauseId
          record.pauseId = null
          record.isPaused = false

          // 重新开始计时
          this.startTimer(record)
          this.$message.success('已继续计时')
        }

        // 更新表格显示
        this.reloadPageTable()
      } catch (error) {
        console.error('暂停/继续操作失败:', error)
        this.$message.error(`操作失败: ${error.message}`)
        // 恢复状态
        record.isPaused = !record.isPaused
      }
    },

    /**
     * 处理计时（开始/结束）
     */
    async handleTiming(record) {
      try {
        if (!record.startTime) {
          // 开始计时
          record.startTime = new Date()
          this.startTimer(record)

          // 调用后端记录开始时间
          await updateStartTimer({
            flowCardNumber: this.flowCardNumber,
            processId: record.id,
            startTime: formatToLocalDateTime(record.startTime),
            reportEmployeeId: Vue.ls.get(USER_INFO).username
          })

          this.$message.success('已开始计时')
        } else if (!record.endTime) {
          // // 结束计时
          // record.endTime = new Date()
          // this.stopTimer(record.id)
          //
          // // 调用后端记录结束时间
          // await updateEndTimer({
          //   flowCardNumber: this.flowCardNumber,
          //   processId: record.id,
          //   endTime: formatToLocalDateTime(record.endTime)
          // })
          //
          // this.$message.success('已完工')

          // 结束计时 - 改为弹出模态框
          this.finishForm = {
            processId: record.id,
            finishedQuantity: null,
            defectiveQuantity: null,
            defectiveReason: null
          }
          this.finishModalVisible = true
        }

        // 刷新表格数据
        this.reloadPageTable()
      } catch (error) {
        console.error('计时操作失败:', error)
        this.$message.error(`操作失败: ${error.message}`)
        // 恢复状态
        if (!record.startTime) {
          record.startTime = null
        } else if (!record.endTime) {
          record.endTime = null
        }
      }
    },

    /**
     * 启动定时器
     */
    startTimer(record) {
      const id = record.id
      this.stopTimer(id) // 先停止已有的定时器

      // 立即计算一次初始值
      this.updateDuration(record)

      // 启动新定时器
      this.activeTimers[id] = setInterval(() => {
        this.updateDuration(record)
      }, this.timerInterval)
    },

    /**
     * 更新动态时间
     */
    updateDuration(record) {
      if (!record || record.isPaused || record.endTime?.trim()) return
      const duration = this.formatDuration(record)
      this.$set(this.activeDurations, record.id, duration)

      // 强制表格刷新当前行
      this.$nextTick(() => {
        const table = this.$refs.table
        if (table && table.$refs.table) {
          const instance = table.$refs.table
          instance.refreshTable && instance.refreshTable()
        }
      })
    },

    /**
     * 停止定时器
     */
    stopTimer(id) {
      if (this.activeTimers[id]) {
        clearInterval(this.activeTimers[id])
        this.$delete(this.activeTimers, id)
        this.$delete(this.activeDurations, id)
      }
    },

    /**
     * 格式化耗时
     */
    formatDuration(record) {

      console.log(record.isPaused)

      if (record?.totalTimeConsumption) {
        let totalSeconds = record.totalTimeConsumption

        if (!record.isPaused && record.status === 1){
          const pauseEndTime = Date.parse(record.pauseEnd) // 避免创建 Date 对象
          const now = Date.now()
          totalSeconds += Math.floor((now - pauseEndTime) / 1000) // 毫秒转秒
        }

        const days = Math.floor(totalSeconds / 86400)
        totalSeconds %= 86400

        const hours = Math.floor(totalSeconds / 3600)
        totalSeconds %= 3600

        const minutes = Math.floor(totalSeconds / 60)
        const seconds = totalSeconds % 60

        // 构建结果字符串（按条件拼接，尽量少创建中间数组）
        let result = ''
        if (days > 0) result += days + '天'
        if (hours > 0 || days > 0) result += hours + '小时'
        if (minutes > 0 || hours > 0 || days > 0) result += minutes + '分钟'
        result += seconds + '秒'

        return result
      } else if (!record?.startTime) return '0小时0分钟0秒'

      const start = new Date(record.startTime)
      const end = record.endTime ? new Date(record.endTime) : new Date()

      // 计算实际工作时间（减去暂停时间）
      let actualDuration = end - start
      if (record.totalPausedTime) {
        actualDuration -= record.totalPausedTime
      }

      // 处理负数情况
      actualDuration = Math.max(0, actualDuration)

      const hours = Math.floor(actualDuration / 3600000)
      const minutes = Math.floor((actualDuration % 3600000) / 60000)
      const seconds = Math.floor((actualDuration % 60000) / 1000)

      return `${hours}小时${minutes}分钟${seconds}秒`
    },

    /**
     * 查询方法
     */
    handleSearch() {
      if (!this.flowCardNumber) {
        this.$message.warning('请输入工序流转单卡号')
        return
      }

      // 清除之前的定时器
      this.clearAllTimers()

      // 加载新数据
      this.reloadPageTable()
    },

    /**
     * 处理预览
     */
    async handlePreview(type, record) {
      try {
        this.previewUrl = ''


        if (record.flowCardNumber === undefined || record.flowCardNumber === ''){
          this.$message.warning('请选择工序流转单卡号')
        }

        if (type === undefined || type === ''){
          this.$message.warning('请选择预览类型')
        }

        // finishedProductImage 成品图片 0
        // processCard 工艺卡 1
        // procedureSheet 程序单 2
        // ncProgram nc程序包  3
        // type 的类型 根据不同传递不同的值

        const typeMap = {
          finishedProductImage: 0,
          processCard: 1,
          procedureSheet: 2,
          ncProgram: 3
        };

        /*// 根据传入的 type 获取数值，找不到默认设为 1（例如 processCard）
        const postData = {
          ProcessCardNumber: record.flowCardNumber,
          type: typeMap[type] !== undefined ? typeMap[type] : 1
        };


        const response = await getCncProgramFile(postData)*/

        if (typeMap[type] === 3){
          getPlmProgramFileNC({
            ProcessCardNumber: record.flowCardNumber,
            type: typeMap[type] !== undefined ? typeMap[type] : 1,
            ProcessCode : record.processCode
          }).then(response => {
            console.log(response.code)
            if (response.code === 1007 || response.data === undefined || response.data === ''){
              this.$message.warning('暂无该文件')
            }else {
              window.open(response.data, '_blank');

            }
            })
        }else {
          getCncProgramFile({
            ProcessCardNumber: record.flowCardNumber,
            type: typeMap[type] !== undefined ? typeMap[type] : 1 ,
            ProcessCode : record.processCode
          })
            .then(blob => {
              if (blob) {
                this.previewUrl = URL.createObjectURL(blob);
                this.$nextTick(() => {
                  this.$refs.pdfViewer.openModal(); // 假设你有 pdfViewer 组件
                });
              }else{
                this.$message.warning('暂无该文件')
              }
            })
            .catch(err => {
              console.error('接口异常:', err);
              this.$message.error(err.message || '下载失败');
            });
        }


      } catch (error) {
        console.error('获取预览文件失败:', error)
        this.$message.error('获取预览文件失败')
      }
    },
    /**
     * 确认完工
     * @returns {Promise<void>}
     */
    async handleFinishConfirm() {
      try {
        // 仅验证必填字段（完工数量）
        await this.$refs.finishForm.validateField('finishedQuantity');

        // 设置结束时间
        const endTime = new Date()

        // 提交数据（选填字段允许为 null）
        await updateEndTimer({
          flowCardNumber: this.flowCardNumber,
          processId: this.finishForm.processId,
          endTime: formatToLocalDateTime(endTime),
          finishedQuantity: this.finishForm.finishedQuantity,
          defectiveQuantity: this.finishForm.defectiveQuantity || null, // 明确传递 null
          defectiveReason: this.finishForm.defectiveReason || null
        });

        // console.log(this.$refs.table.localDataSource)

        // 更新前端状态
        const record = this.$refs.table.localDataSource.find(item => item.id === this.finishForm.processId)
        if (record) {
          record.endTime = endTime
          this.stopTimer(record.id)
        }

        this.$message.success('已完工')
        this.finishModalVisible = false
        this.reloadPageTable()
      } catch (error) {
        if (error.name !== 'ValidationError') {
          console.error('完工操作失败:', error)
          this.$message.error(`操作失败: ${error.message}`)
        }
      }
    }
  }
}
</script>

<style scoped>
.work-report-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.content-area {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.work-form {
  padding: 20px 0;
}

/* 按钮样式 */
.btn-start {
  color: #52c41a; /* 绿色 */
  cursor: pointer;
  transition: all 0.3s;
}

.btn-start:hover {
  color: #73d13d;
}

.btn-stop {
  color: #ff4d4f; /* 红色 */
  cursor: pointer;
  transition: all 0.3s;
}

.btn-stop:hover {
  color: #ff7875;
}

.btn-pause {
  color: #faad14; /* 黄色 */
  cursor: pointer;
  transition: all 0.3s;
}

.btn-pause:hover {
  color: #ffc53d;
}

.time-display {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 操作列样式 */
.ant-table td {
  padding: 12px 8px !important;
}

/* 禁用状态样式 */
[disabled] {
  color: rgba(0, 0, 0, 0.25) !important;
  cursor: not-allowed !important;
}

/* 可以添加一些样式美化模态框 */
.ant-modal-body {
  padding: 24px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>
